<template>
  <!-- 中间地图模块 -->
  <div class="map_box">
    <!-- 中国地图 -->
    <div id="china-map" class="map" style="width: 100%; height: 1100px" />
  </div>
</template>

<script>
import { EventBus } from '../../../utils/eventbus' // 引入事件中心
import router from '@/router'
import chinas from '../echarts/china.json'
import { getDataIDApi, getChinaApi } from '@/api/user'
export default {
  name: 'QsgSystemMap',
  props: {
    // dataList: {
    //   type: Array,
    //   default: () => {
    //     return []
    //   }
    // },
    Lableres: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      Lableres1: [
        {
          name: '数据加载中',
          coords: [
            [120.19, 30.26],
            [102.7129, 38.166]
          ], // 线条位置[开始位置，结束位置]
          value: ['粮食作物']
        }
      ],
      Lableres2: [],
      chinaNext: null,
      dataList: [],
      LableList: {},
      firstTop: 1
    }
  },
  async mounted() {
    // EventBus.$on('addition', (param) => {
    //   this.Lableres2 = param.data
    //   console.log(this.Lableres2)
    //   this.china_map(this.Lableres2)
    // })
    // 中国地图
    this.handleScroll()
    await this.getDataId()
    await this.$nextTick(() => {
      this.china_map(this.Lableres1)
    })
  },

  methods: {
    // 获取点位数据 , projectType: 2
    async getDataId(province) {
      const Lableres = await getDataIDApi({ provinceOnly: province, projectType: 2 })
      this.dataList = Lableres
      this.LableList = {}
      this.dataList.forEach(item => {
        if (!this.LableList[item.provinceOnly]) {
          this.LableList[item.provinceOnly] = []
        }
        this.LableList[item.provinceOnly].push(item)
      })
      if (this.firstTop === 1) {
        this.dataList = []
        const dataListName = []
        Object.keys(this.LableList).forEach(item => {
          dataListName.push(item)
        })
        chinas.features.map(item => {
          if (dataListName.includes(item.properties.name)) {
            this.dataList.push({
              name: item.properties.name,
              geoInfo: item.properties.centroid.toString()
            })
          }
        })
      }
    },
    // 地图JSON数据
    async getChina(code) {
      const res = await getChinaApi({ code: code })
      this.chinaNext = res
    },
    // 鼠标滚动
    handleScroll() {
      let setTime = null
      const vm = this
      window.addEventListener('wheel', // wheel：在浏览器窗口滚动鼠标滚轮时触发
        async function(e) {
          if (e.deltaY < 0) {
            if (setTime) {
              clearTimeout(setTime)
            }
            vm.chinaNext = ''
            vm.firstTop = 1
            setTime = setTimeout(async() => {
              await vm.getDataId()
              vm.$nextTick(async() => {
                await vm.china_map()
              })
            }, 1000)
          }
        }
      )
    },
    // 中国地图
    china_map(data) {
      const vm = this
      const iconGD = 'image://'
      const iconImportant = 'image://'
      const iconGDBack = 'image://'
      const logoImg = 'image://'
      const mapChart = this.$echarts.init(document.getElementById('china-map')) // 图表初始化，china-map是绑定的元素
      this.$echarts.registerMap('chinas', this.chinaNext ? this.chinaNext : chinas)
      window.onresize = mapChart.resize // 如果容器变大小，自适应从新构图
      let series = [] // 存放循环配置项
      const mapTexture = document.createElement('img')
      mapTexture.src = require('@/assets/shaw.png')
      mapTexture.onload = function() {
        // 获取地图元素
        const echartContainer = document.getElementById('china-map')
        // 创建临时元素
        const canvasBackgroundImg = document.createElement('canvas')
        // 重新裁剪图片，适应元素宽高
        canvasBackgroundImg.width = echartContainer.clientWidth
        canvasBackgroundImg.height = echartContainer.clientHeight
        const ctx = canvasBackgroundImg.getContext('2d')
        ctx.drawImage(mapTexture, 0, 0, echartContainer.clientWidth, echartContainer.clientHeight)
        const dataMap = []
        Object.keys(vm.LableList).map(item => {
          dataMap.push({
            name: item,
            // 自定义区域的颜色
            itemStyle: {
              areaColor: {
                image: canvasBackgroundImg,
                repeat: 'repeat'
              }
            }
          })
        })
        // 循环往series内添加配置项
        series.push(
          // 点击高亮
          {
            type: 'map',
            mapType: 'chinas',
            zlevel: 1,
            // roam: true,
            tooltip: {
              show: true
            },
            selectedMode: 'disabled', // 选择模式，单选，只能选中一个地市
            // 这个就是鼠标点击后高亮状态，地图想要展示的配置
            select: {
              disabled: true,
              label: {
                // 选中区域的label(文字)样式
                color: '#fff'
              },
              itemStyle: {
                olor: '#fff',
                borderColor: '#29bbd8',
                areaColor: '#3bb8f7',
                shadowBlur: 3,
                borderWidth: 1,
                shadowOffsetX: 2,
                shadowOffsetY: 2,
                shadowColor: '#3bb8f7',
                opacity: 0
              }
            },
            label: {
              normal: {
                show: true, // 是否显示省份名字，现在是隐藏的状态，因为和散点图的名字重叠了。如果需要就true
                textStyle: {
                  // 名字的样式
                  color: '#fff'
                }
              },
              emphasis: {
                show: true,
                textStyle: {
                  // 名字的样式
                  color: '#fff'
                }
              }
            },
            itemStyle: {
              normal: {
                show: true,
                areaColor: 'rgb(0 0 0 / 85%)',
                borderColor: '#1da8c0',
                borderWidth: 1
              },
              emphasis: {
                show: true,
                areaColor: '#0014ff40',
                borderWidth: 0
              }
            },
            data: dataMap
          }
        )
        const dataList = []
        let dataIndex = -1
        vm.dataList.map(item => {
          if (!item.geoInfo) {
            return
          }
          if (item.geoInfo === '120.498,29.0918') {
            dataIndex++
          }
          dataList.push({
            name: item.name,
            type: 'scatter',
            zlevel: 2,
            coordinateSystem: 'geo',
            data: [{
              name: item.name,
              value: item.geoInfo ? item.geoInfo.split(',') : [],
              type: '',
              id: item.id
            }],
            symbol: iconGD,
            symbolSize: '25',
            hoverAnimation: true,
            label: {
              normal: {
                show: false,
                formatter: (params) => {
                  return params.name
                },
                position: 'right',
                color: '#fff',
                fontSize: '8'
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                color: '#ea6347',
                borderWidth: 2,
                borderColor: '#f4b391'
              }
            }
          })
          if (vm.firstTop === 2) {
            dataList.push({
              type: 'scatter',
              zlevel: 2,
              coordinateSystem: 'geo',
              data: [{
                name: item.name,
                value: item.geoInfo ? item.geoInfo.split(',') : [],
                type: '',
                id: item.id
              }],
              symbol: 'rect',
              symbolSize: [item.name.length * 15, 35],
              symbolOffset: [0, 35],
              label: {
                normal: {
                  show: true,
                  formatter: (params) => {
                    return params.name
                  },
                  padding: [0, 0, 0, 0],
                  lineHeight: 35,
                  fontWeight: 'bold',
                  position: 'inside',
                  verticalAlign: 'middle',
                  color: '#fff',
                  fontSize: '14'
                },
                emphasis: {
                  show: true
                }
              },
              itemStyle: {
                normal: {
                  color: '#4693ff6e',
                  areaColor: '#4693ff6e'
                }
              }
            })
          }
        })
        series = [...series, ...dataList]
        // 配置
        const option = {
          animationDuration: 4000, // 线条渲染速度1000 === 1s
          legend: {
            show: true,
            x: 'left',
            orient: 'vertical',
            textStyle: {
              color: 'white'
            },
            data: []
          },
          // visualMap: {
          //   min: 0,
          //   max: 1500,
          //   left: 'left',
          //   top: 'bottom',
          //   text: ['高', '低'],
          //   calculable: true,
          //   // seriesIndex: [1],
          //   inRange: {
          //     color: ['#e0ffff', '#006edd']
          //   },
          //   show: false
          // },
          // 鼠标移上去的弹框
          tooltip: {
            trigger: 'item',
            show: true,
            color: '#fff',
            fontSize: '16',
            backgroundColor: '#ffffff00',
            borderWidth: 0,
            position: function(point, params, dom, rect, size) {
              // 固定在顶部
              return [point[0] - params.name.length * 8, point[1] + 25]
            },
            formatter: (params) => {
              // 根据业务自己拓展要显示的内容
              const name = params.name
              // const value = params.value
              let res = null
              if (params.seriesType === 'scatter') {
                res = `<div class="box_line">${name}</div>`
              }
              return res
            }
          },
          geo: {
            show: true,
            roam: false,
            animationDurationUpdate: 0,
            map: 'chinas',
            selectedMode: 'disabled', // 选择模式，单选，只能选中一个地市
            // 这个就是鼠标点击后高亮状态，地图想要展示的配置
            label: {
              normal: {
                show: false, // 是否显示省份名字，现在是隐藏的状态，因为和散点图的名字重叠了。如果需要就true
                textStyle: {
                  // 名字的样式
                  color: '#fff'
                }
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                show: false,
                areaColor: {
                  image: canvasBackgroundImg,
                  repeat: 'repeat'
                },
                borderColor: '#03f6f8',
                borderWidth: 2,
                shadowColor: '#03f6f8',
                shadowBlur: 7
                // areaColor: '#00000000',
                // borderWidth: 4,
                // borderColor: '#03f6f8'
              },
              emphasis: {
                show: false,
                areaColor: '#000'
              }
            }
          },
          series: series
        }

        mapChart.setOption(option, true) // 生成图表
        const currentHighlight = null
        // 地图点击事件
        mapChart.on('click', async function(params) {
          // if (currentHighlight) {
          //   mapChart.dispatchAction({
          //     type: 'downplay',
          //     seriesIndex: 0,
          //     name: params.name
          //   })
          // }
          // 高亮点击的区域
          // mapChart.dispatchAction({
          //   type: 'highlight',
          //   seriesIndex: 0,
          //   name: params.name
          // })
          // 记录当前高亮的区域
          if (params?.data?.id && params.seriesType === 'scatter') {
            vm.$emit('getContentList', params.data.id)
            return
          }
          let clickRegionCode = ''
          let province = ''
          chinas.features.map((areaJson) => {
            if (areaJson.properties.name === params.name) {
              clickRegionCode = areaJson?.properties?.adcode
              province = areaJson?.properties?.name
            }
          })
          if (!clickRegionCode) {
            return
          }
          vm.firstTop = 2
          await vm.getDataId(province)
          await vm.getChina(clickRegionCode)
          await vm.china_map()
          // vm.china_map()
          // vm.$emit('getContentList', params.data.id)
          // router.push(`/meilin/${params.data.id}`)
        })
      }
      // 加载echart 配置
    }
  }
}
</script>

<style lang="scss" scoped>
.map_box {
  width: 100%;
  height: 100%;
  position: relative;
  margin-top: -105px;
}
.map {
  // width: 1920px;
  // height: 900px;
}
</style>
